<!DOCTYPE html>
<html>
<head>
    <title>销售信息录入</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .sale-form {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .form-group textarea {
            height: 80px;
            resize: vertical;
        }
        .form-row {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
        }
        .form-row .form-group {
            flex: 1;
            margin-bottom: 0;
        }
        .required::after {
            content: " *";
            color: #d32f2f;
        }
        .submit-btn {
            background-color: #c0a36c;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        .submit-btn:hover {
            background-color: #a88c5a;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error {
            color: #d32f2f;
            padding: 10px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        .success {
            color: #2e7d32;
            padding: 10px;
            background-color: #e8f5e8;
            border-radius: 4px;
            margin: 10px 0;
        }
        .price-input {
            text-align: right;
        }
        .datetime-input {
            width: 100%;
        }
        .readonly-input {
            background-color: #f5f5f5;
            cursor: not-allowed;
        }
    </style>
</head>
<body style="background-color:#fffbf6">
    
    <!-- 状态栏 -->
    {% include 'status_bar.html' %}
    
    <!-- 返回主菜单按钮 -->
    <div style="max-width: 1200px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div>
    
    <h2 style="max-width: 1200px; margin: 0 auto 20px auto; padding: 0 20px;">销售信息录入</h2>

    <!-- 搜索区域 -->
    <div class="sale-form" style="margin-bottom: 20px;">
        <h4 style="margin-bottom: 15px;">搜索库存</h4>
        
        <!-- 搜索方式选择 -->
        <div class="form-group" style="margin-bottom: 15px;">
            <label style="font-weight: bold; margin-bottom: 8px;">搜索方式:</label>
            <div style="display: flex; flex-wrap: wrap; gap: 15px;">
                <label style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="colors" checked style="margin-right: 5px;"> 按颜色
                </label>
                <label style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="wu_xings" style="margin-right: 5px;"> 按五行
                </label>
                <label style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="major_material" style="margin-right: 5px;"> 按材质
                </label>
                <label style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="stock_id" style="margin-right: 5px;"> 按库存编号
                </label>
                <label style="display: flex; align-items: center; white-space: nowrap;">
                    <input type="radio" name="searchType" value="product_id" style="margin-right: 5px;"> 按产品ID
                </label>
            </div>
        </div>
        
        <!-- 搜索输入框和按钮 -->
        <div class="form-row">
            <div class="form-group" style="flex: 2;">
                <input type="text" id="searchInput" class="search-input" placeholder="输入搜索关键词..." style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px;">
            </div>
            <div class="form-group" style="flex: 1;">
                <button onclick="filterStocks()" class="search-button" style="padding: 8px 16px; background-color: #c0a36c; color: white; border: none; border-radius: 4px; cursor: pointer; width: 100%;">搜索</button>
            </div>
            <div class="form-group" style="flex: 1;">
                <button onclick="clearSearch()" class="search-button" style="padding: 8px 16px; background-color: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer; width: 100%;">重置</button>
            </div>
        </div>
        
        <div style="margin-top: 10px; font-size: 12px; color: #666;">
            提示：五行和颜色搜索支持多字符（如"火土"），将匹配包含火、土或火土的产品；产品ID和库存编号支持精确或部分匹配
        </div>
    </div>

    <!-- 库存编号选择器 -->
    <div class="sale-form" style="margin-bottom: 20px;">
        <div class="form-group">
            <label class="required">库存编号筛选</label>
            <select id="stock_filter" style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px;">
                <option value="all">全部有效库存</option>
            </select>
        </div>
    </div>

    <div id="loading" class="loading" style="display: none;">正在加载...</div>
    <div id="error" class="error" style="display: none;"></div>
    <div id="success" class="success" style="display: none;"></div>

    <!-- 所有库存的销售表单容器 -->
    <div id="saleFormsContainer"></div>

    <form id="saleForm" class="sale-form" style="display: none;">
        <!-- 销售基本信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">销售时间</label>
                <input type="datetime-local" id="sale_datetime" name="sale_datetime" class="datetime-input" required>
            </div>
            <div class="form-group">
                <label class="required">库存编号</label>
                <select id="stock_id" name="stock_id" required>
                    <option value="">请选择库存</option>
                </select>
            </div>
        </div>

        <!-- 买家信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">买家ID</label>
                <input type="text" id="buyer_id" name="buyer_id" required placeholder="请输入买家ID">
            </div>
            <div class="form-group">
                <label class="required">买家姓名</label>
                <input type="text" id="buyer_name" name="buyer_name" required placeholder="请输入买家姓名">
            </div>
        </div>

        <!-- 销售员信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">销售员ID</label>
                <input type="text" id="saler_id" name="saler_id" required placeholder="请输入销售员ID">
            </div>
            <div class="form-group">
                <label class="required">销售员姓名</label>
                <input type="text" id="saler_name" name="saler_name" required placeholder="请输入销售员姓名">
            </div>
        </div>

        <!-- 价格信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">销售价格 (元)</label>
                <input type="number" step="0.01" id="sale_price" name="sale_price" value="0.00" class="price-input" min="0" required onchange="calculatePrices()">
            </div>
            <div class="form-group">
                <label class="required">销售数量</label>
                <input type="number" step="0.01" id="sale_qty" name="sale_qty" value="1.00" class="price-input" min="0.01" required onchange="calculatePrices()">
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label>销售折扣 (%)</label>
                <input type="number" step="0.01" id="sale_discount" name="sale_discount" value="0.00" class="price-input" min="0" max="100" onchange="calculatePrices()">
            </div>
            <div class="form-group">
                <label class="required">实际价格 (元)</label>
                <input type="number" step="0.01" id="sale_real_price" name="sale_real_price" value="0.00" class="price-input readonly-input" readonly>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group">
                <label class="required">总价格 (元)</label>
                <input type="number" step="0.01" id="sale_total_price" name="sale_total_price" value="0.00" class="price-input readonly-input" readonly>
            </div>
            <div class="form-group">
                <label>结算价格 (元)</label>
                <input type="number" step="0.01" id="settled_price" name="settled_price" value="0.00" class="price-input" min="0">
            </div>
        </div>

        <!-- 结算时间 -->
        <div class="form-row">
            <div class="form-group">
                <label>结算时间</label>
                <input type="datetime-local" id="settled_datetime" name="settled_datetime" class="datetime-input">
            </div>
            <div class="form-group">
                <!-- 空占位格 -->
            </div>
        </div>

        <!-- 库存信息显示 -->
        <div class="form-group" id="stock_info_container" style="display: none; padding: 15px; background-color: #f9f9f9; border-radius: 4px; border: 1px solid #ddd;">
            <h4>库存信息</h4>
            <div id="stock_info"></div>
        </div>

        <!-- 备注 -->
        <div class="form-group">
            <label>备注</label>
            <textarea id="comment" name="comment" placeholder="请输入备注信息"></textarea>
        </div>

        <button type="submit" class="submit-btn">提交销售信息</button>
    </form>

    <script src="../static/js/common.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../static/js/ejj_functions.js"></script>
    <script>
        let validStocks = []; // 存储有效库存数据
        let filteredStocks = []; // 存储筛选后的库存数据
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 先加载销售员配置，配置加载完成后再加载库存数据
            loadSalerConfig().then(() => {
                // 销售员配置加载完成后，加载有效库存数据
                loadValidStockData();
                
                // 库存筛选器改变事件
                document.getElementById('stock_filter').addEventListener('change', function() {
                    const selectedStockId = this.value;
                    if (selectedStockId === 'all') {
                        showAllStockForms();
                    } else {
                        showSingleStockForm(selectedStockId);
                    }
                });
                
                // 搜索输入框实时搜索（防抖）
                let searchTimeout;
                document.getElementById('searchInput').addEventListener('input', function() {
                    clearTimeout(searchTimeout);
                    searchTimeout = setTimeout(filterStocks, 300);
                });
                
                // 搜索方式改变事件
                document.querySelectorAll('input[name="searchType"]').forEach(radio => {
                    radio.addEventListener('change', filterStocks);
                });
                
                // 搜索输入框回车键搜索
                document.getElementById('searchInput').addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        filterStocks();
                    }
                });
            }).catch(error => {
                console.error('销售员配置加载失败:', error);
                // 即使销售员配置加载失败，也继续加载库存数据
                loadValidStockData();
            });
        });

        // 加载销售员配置
        function loadSalerConfig() {
            return fetch('/get_ejj_jade_json_config')
                .then(response => response.json())
                .then(data => {
                    if (data.config && data.config.saler) {
                        window.salerConfig = data.config.saler;
                        console.log('销售员配置加载成功:', window.salerConfig);
                    }
                    return data;
                })
                .catch(error => {
                    console.error('加载销售员配置失败:', error);
                    throw error;
                });
        }

        // 加载有效库存数据
        function loadValidStockData() {
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            
            loading.style.display = 'block';
            error.style.display = 'none';

            fetch('/get_valid_stock_ids')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    loading.style.display = 'none';
                    if (data.res === 'ok' && data.data) {
                        validStocks = data.data;
                        console.log('获取到的库存数据:', data.data);
                        initStockFilterOptions();
                        // 默认显示所有库存表单
                        showAllStockForms();
                    } else {
                        throw new Error(data.message || '数据格式错误');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载有效库存数据失败: ' + error.message;
                });
        }

        // 初始化库存筛选选项
        function initStockFilterOptions() {
            const stockFilter = document.getElementById('stock_filter');
            
            // 清空现有选项（保留"全部有效库存"）
            while (stockFilter.options.length > 1) {
                stockFilter.remove(1);
            }
            
            // 添加所有有效库存选项
            validStocks.forEach(stock => {
                const option = document.createElement('option');
                option.value = stock.stock_id;
                option.textContent = `${stock.stock_id} (可用: ${stock.available_qty})`;
                stockFilter.appendChild(option);
            });
        }

        // 显示所有库存的表单
        function showAllStockForms() {
            const container = document.getElementById('saleFormsContainer');
            container.innerHTML = '';
            
            validStocks.forEach(stock => {
                const formHtml = createStockForm(stock);
                container.innerHTML += formHtml;
            });
            
            // 为所有表单添加事件监听
            attachFormEventListeners();
        }

        // 显示单个库存的表单
        function showSingleStockForm(stockId) {
            const container = document.getElementById('saleFormsContainer');
            container.innerHTML = '';
            
            const stock = validStocks.find(s => s.stock_id === stockId);
            if (stock) {
                const formHtml = createStockForm(stock);
                container.innerHTML = formHtml;
                
                // 为表单添加事件监听
                attachFormEventListeners();
            }
        }

        // 创建单个库存的销售表单
        function createStockForm(stock) {
            const now = new Date();
            const localDateTime = now.toISOString().slice(0, 16);
            
            // 构建产品图片URL
            const productImageUrl = stock.product_id ? `/serve_jade_image?product_id=${stock.product_id}` : '';
            
            // 调试信息：输出当前库存的成本数据
            console.log('当前库存成本数据:', {
                stock_id: stock.stock_id,
                material_price: stock.material_price,
                manual_price: stock.manual_price,
                transfer_price: stock.transfer_price,
                other_price: stock.other_price,
                has_cost_data: stock.material_price || stock.manual_price || stock.transfer_price || stock.other_price
            });
            
            return `
                <form class="sale-form stock-form" data-stock-id="${stock.stock_id}">
                    <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                        <div>
                            <h4 style="margin: 0 0 10px 0;">库存编号: ${stock.stock_id}</h4>
                            <p style="margin: 5px 0;">
                                <span style="color: #666;">产品ID: </span>
                                ${stock.product_id ? `
                                <span style="color: #333;">
                                    ${stock.product_id}
                                </span>
                                ` : '<span style="color: #666;">无</span>'}
                            </p>
                            <p style="margin: 5px 0; color: #666;">可用数量: ${stock.available_qty}</p>
                            ${stock.material_price || stock.manual_price || stock.transfer_price || stock.other_price ? `
                            <p style="margin: 5px 0; color: #666;">
                                成本信息: 材料 ${parseFloat(stock.material_price || 0).toFixed(2)} + 手工 ${parseFloat(stock.manual_price || 0).toFixed(2)} + 运输 ${parseFloat(stock.transfer_price || 0).toFixed(2)} + 其他 ${parseFloat(stock.other_price || 0).toFixed(2)} = ${(parseFloat(stock.material_price || 0) + parseFloat(stock.manual_price || 0) + parseFloat(stock.transfer_price || 0) + parseFloat(stock.other_price || 0)).toFixed(2)}元
                            </p>
                            ` : ''}
                        </div>
                        ${productImageUrl ? `
                        <div style="flex-shrink: 0;">
                            <img src="${productImageUrl}" alt="产品图片" 
                                 style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px; border: 1px solid #ddd;">
                        </div>
                        ` : ''}
                    </div>
                    
                    <!-- 销售基本信息 -->
                    <div class="form-row">
                        <div class="form-group">
                            <label class="required">销售时间</label>
                            <input type="datetime-local" name="sale_datetime" class="datetime-input" value="${localDateTime}" required>
                        </div>
                        <div class="form-group">
                            <label class="required">库存编号</label>
                            <input type="text" name="stock_id" value="${stock.stock_id}" class="readonly-input" readonly>
                        </div>
                    </div>

        <!-- 买家信息 -->
        <div class="form-row">
            <div class="form-group">
                <label>买家ID</label>
                <input type="text" name="buyer_id" placeholder="请输入买家ID（可选）">
            </div>
            <div class="form-group">
                <label class="required">买家姓名</label>
                <input type="text" name="buyer_name" placeholder="请输入买家姓名" required>
            </div>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label>买家公司</label>
                <input type="text" name="buyer_company" placeholder="请输入买家公司（可选）">
            </div>
            <div class="form-group">
                <!-- 空占位格 -->
            </div>
        </div>

        <!-- 销售员信息 -->
        <div class="form-row">
            <div class="form-group">
                <label class="required">销售员</label>
                <select id="saler_select" name="saler_info" required>
                    <option value="">请选择销售员</option>
                </select>
            </div>
            <div class="form-group">
                <!-- 空占位格 -->
            </div>
        </div>

                    <!-- 价格信息 -->
                    <div class="form-row">
                        <div class="form-group">
                            <label class="required">销售价格 (元)</label>
                            <input type="number" step="0.01" name="sale_price" value="0.00" class="price-input" min="0" required onchange="calculatePrices(this)">
                        </div>
                        <div class="form-group">
                            <label class="required">销售数量</label>
                            <input type="number" name="sale_qty" value="1" class="price-input" min="1" max="${stock.available_qty}" required onchange="calculatePrices(this)">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>销售折扣 (%)</label>
                            <input type="number" step="0.01" name="sale_discount" value="0.00" class="price-input" min="0" max="100" onchange="calculatePrices(this)">
                        </div>
                        <div class="form-group">
                            <label class="required">实际价格 (元)</label>
                            <input type="number" step="0.01" name="sale_real_price" value="0.00" class="price-input readonly-input" readonly>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="required">总价格 (元)</label>
                            <input type="number" step="0.01" name="sale_total_price" value="0.00" class="price-input readonly-input" readonly>
                        </div>
                        <div class="form-group">
                            <!-- 空占位格 -->
                        </div>
                    </div>

                    <!-- 备注 -->
                    <div class="form-group">
                        <label>备注</label>
                        <textarea name="comment" placeholder="请输入备注信息"></textarea>
                    </div>

                    <button type="submit" class="submit-btn">提交销售信息</button>
                </form>
            `;
        }

        // 为所有表单添加事件监听
        function attachFormEventListeners() {
            const forms = document.querySelectorAll('.stock-form');
            forms.forEach(form => {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(this);
                    const data = Object.fromEntries(formData.entries());
                    
                    // 添加时间戳
                    data.created_at = new Date().toISOString();
                    data.updated_at = new Date().toISOString();
                    
                    // 验证数据
                    if (!validateForm(data, this)) {
                        return;
                    }
                    
                    // 发送数据到后端
                    submitSaleData(data, this);
                });

                // 价格输入框格式化
                const priceInputs = form.querySelectorAll('.price-input');
                priceInputs.forEach(input => {
                    input.addEventListener('blur', function() {
                        if (this.value === '') {
                            this.value = '0.00';
                        } else {
                            this.value = parseFloat(this.value).toFixed(2);
                        }
                    });
                    
                    input.addEventListener('focus', function() {
                        if (this.value === '0.00') {
                            this.value = '';
                        }
                    });
                });

                // 初始化销售员下拉菜单
                initSalerSelect(form);
            });
        }

        // 初始化销售员下拉菜单
        function initSalerSelect(form) {
            const salerSelect = form.querySelector('#saler_select');
            if (salerSelect && window.salerConfig) {
                // 清空现有选项
                salerSelect.innerHTML = '<option value="">请选择销售员</option>';
                
                // 添加销售员选项
                window.salerConfig.forEach(saler => {
                    const option = document.createElement('option');
                    option.value = saler.id;
                    option.textContent = `${saler.id} - ${saler.name}`;
                    option.dataset.salerName = saler.name;
                    salerSelect.appendChild(option);
                });
            }
        }


        // 计算价格 - 支持两种调用方式：calculatePrices() 和 calculatePrices(this)
        function calculatePrices(inputElement) {
            let form;
            
            // 处理不同的调用方式
            if (inputElement && inputElement.closest) {
                // 带参数的调用：calculatePrices(this)
                form = inputElement.closest('form');
            } else {
                // 不带参数的调用：calculatePrices() - 使用主表单
                form = document.getElementById('saleForm');
            }
            
            if (!form) {
                console.error('无法找到表单元素');
                return;
            }
            
            const salePrice = parseFloat(form.querySelector('[name="sale_price"]').value) || 0;
            const saleQty = parseFloat(form.querySelector('[name="sale_qty"]').value) || 0;
            const saleDiscount = parseFloat(form.querySelector('[name="sale_discount"]').value) || 0;
            
            // 计算实际价格（销售价格 × 销售折扣）
            let realPrice = salePrice;
            if (saleDiscount > 0) {
                realPrice = salePrice * (saleDiscount / 100);
            }
            
            // 计算总价格
            const totalPrice = realPrice * saleQty;
            
            // 更新显示
            form.querySelector('[name="sale_real_price"]').value = realPrice.toFixed(2);
            form.querySelector('[name="sale_total_price"]').value = totalPrice.toFixed(2);
            
            // 自动设置结算价格为总价格（如果结算价格为空）
            const settledPrice = form.querySelector('[name="settled_price"]');
            if (settledPrice && (!settledPrice.value || settledPrice.value === '0.00')) {
                settledPrice.value = totalPrice.toFixed(2);
            }
        }

        // 表单验证
        function validateForm(data, form) {
            const error = document.getElementById('error');
            error.style.display = 'none';

            // 检查必填字段（买家ID不是必须，但买家姓名是必须）
            const requiredFields = [
                'sale_datetime', 'stock_id', 'saler_info', 'buyer_name', 'sale_price', 'sale_qty'
            ];
            
            for (const field of requiredFields) {
                if (!data[field] || data[field].toString().trim() === '') {
                    showError(`${getFieldName(field)}不能为空`);
                    return false;
                }
            }

            // 检查数字字段是否为有效数字（移除settled_price）
            const numberFields = ['sale_price', 'sale_qty', 'sale_discount', 'sale_real_price', 'sale_total_price'];
            for (const field of numberFields) {
                const value = parseFloat(data[field]);
                if (isNaN(value) || value < 0) {
                    showError(`${getFieldName(field)}必须为有效的非负数`);
                    return false;
                }
            }

            // 检查销售数量是否为整数
            const saleQty = parseFloat(data.sale_qty);
            if (!Number.isInteger(saleQty)) {
                showError('销售数量必须是整数');
                return false;
            }

            // 检查销售数量是否大于0
            if (saleQty <= 0) {
                showError('销售数量必须大于0');
                return false;
            }

            // 检查销售数量是否超过可用库存
            const stockId = data.stock_id;
            const stock = validStocks.find(s => s.stock_id === stockId);
            if (stock && saleQty > parseFloat(stock.available_qty)) {
                showError(`销售数量不能超过可用库存量 (${stock.available_qty})`);
                return false;
            }

            return true;
        }

        // 获取字段中文名称
        function getFieldName(field) {
            const fieldNames = {
                'sale_datetime': '销售时间',
                'stock_id': '库存编号',
                'buyer_id': '买家ID',
                'buyer_name': '买家姓名',
                'saler_id': '销售员',
                'saler_name': '销售员姓名',
                'sale_price': '销售价格',
                'sale_qty': '销售数量',
                'sale_discount': '销售折扣',
                'sale_real_price': '实际价格',
                'sale_total_price': '总价格'
            };
            return fieldNames[field] || field;
        }

        // 显示错误信息
        function showError(message) {
            const error = document.getElementById('error');
            error.style.display = 'block';
            error.textContent = message;
            
            // 3秒后自动隐藏错误信息
            setTimeout(() => {
                error.style.display = 'none';
            }, 3000);
        }

        // 显示成功信息
        function showSuccess(message) {
            const success = document.getElementById('success');
            success.style.display = 'block';
            success.textContent = message;
            
            // 3秒后自动隐藏成功信息
            setTimeout(() => {
                success.style.display = 'none';
            }, 3000);
        }

        // 重新加载有效的库存数据
        function reloadValidStockData() {
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            
            loading.style.display = 'block';
            error.style.display = 'none';

            fetch('/get_valid_stock_ids')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    loading.style.display = 'none';
                    if (data.res === 'ok' && data.data) {
                        validStocks = data.data;
                        initStockFilterOptions();
                        
                        // 根据当前筛选状态重新显示表单
                        const selectedFilter = document.getElementById('stock_filter').value;
                        if (selectedFilter === 'all') {
                            showAllStockForms();
                        } else {
                            showSingleStockForm(selectedFilter);
                        }
                        
                        showSuccess('库存数据已更新！');
                    } else {
                        throw new Error(data.message || '数据格式错误');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '重新加载库存数据失败: ' + error.message;
                });
        }

        // 提交销售数据
        function submitSaleData(data, form) {
            const submitBtn = form.querySelector('.submit-btn');
            const error = document.getElementById('error');
            const success = document.getElementById('success');
            
            submitBtn.disabled = true;
            submitBtn.textContent = '提交中...';
            error.style.display = 'none';
            success.style.display = 'none';

            // 处理销售员信息（将ID-姓名格式拆分为saler_id和saler_name）
            if (data.saler_info) {
                const salerParts = data.saler_info.split(' - ');
                data.saler_id = salerParts[0]; // 提取ID部分
                data.saler_name = salerParts[1] || ''; // 提取姓名部分
                delete data.saler_info; // 删除原始字段
            }

            // 显示加载中
            const loading = document.getElementById('loading');
            loading.style.display = 'block';

            fetch('/deal_ej_sale', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => {
                loading.style.display = 'none';
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    showSuccess('销售信息保存成功！正在更新库存数据...');
                    
                    // 清空表单
                    form.reset();
                    // 重置时间字段
                    const now = new Date();
                    const localDateTime = now.toISOString().slice(0, 16);
                    
                    // 安全地重置字段值，检查元素是否存在
                    const setFieldValue = (selector, value) => {
                        const element = form.querySelector(selector);
                        if (element) {
                            element.value = value;
                        }
                    };
                    
                    setFieldValue('[name="sale_datetime"]', localDateTime);
                    // 重置价格字段
                    setFieldValue('[name="sale_price"]', '0.00');
                    setFieldValue('[name="sale_qty"]', '1.00');
                    setFieldValue('[name="sale_discount"]', '0.00');
                    setFieldValue('[name="sale_real_price"]', '0.00');
                    setFieldValue('[name="sale_total_price"]', '0.00');
                    setFieldValue('[name="settled_price"]', '0.00');
                    
                    // 重新加载有效的库存数据并更新界面
                    reloadValidStockData();
                } else {
                    throw new Error(result.message || '保存失败');
                }
            })
            .catch(error => {
                showError('保存失败: ' + error.message);
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.textContent = '提交销售信息';
            });
        }

        // 搜索库存
        function filterStocks() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const searchType = document.querySelector('input[name="searchType"]:checked').value;
            
            if (!searchTerm) {
                // 如果搜索词为空，显示所有库存
                showAllStockForms();
                return;
            }
            
            // 筛选库存数据
            filteredStocks = validStocks.filter(stock => {
                const fieldValue = stock[searchType];
                if (!fieldValue) return false;
                
                const fieldValueLower = fieldValue.toLowerCase();
                
                // 对于五行和颜色搜索，支持多字符匹配（OR逻辑）
                if (searchType === 'wu_xings' || searchType === 'colors') {
                    // 检查是否包含搜索词中的任意字符或整个搜索词
                    return searchTerm.split('').some(char => fieldValueLower.includes(char)) || 
                           fieldValueLower.includes(searchTerm);
                } else {
                    // 其他字段使用原来的包含匹配
                    return fieldValueLower.includes(searchTerm);
                }
            });
            
            // 显示筛选结果
            displayFilteredStocks(filteredStocks);
        }

        // 显示筛选后的库存
        function displayFilteredStocks(stocks) {
            const container = document.getElementById('saleFormsContainer');
            container.innerHTML = '';
            
            if (stocks.length === 0) {
                container.innerHTML = '<div class="loading">没有找到匹配的库存</div>';
                return;
            }
            
            stocks.forEach(stock => {
                const formHtml = createStockForm(stock);
                container.innerHTML += formHtml;
            });
            
            // 为所有表单添加事件监听
            attachFormEventListeners();
        }

        // 清空搜索
        function clearSearch() {
            document.getElementById('searchInput').value = '';
            showAllStockForms();
        }
    </script>
</body>
</html>
